package Lock;

public class DeadLock {
    public static void main(String[] args) {
        Makeup g1=new Makeup("灰姑娘",0);
        Makeup g2=new Makeup("白雪公主",1);
        g1.start();
        g2.start();
    }
}
class Lipstick{
}
class Mirror{
}

class Makeup extends Thread{
    // only one
    static Lipstick lipstick=new Lipstick();
    static Mirror mirror=new Mirror();

    int choice;
    String username;

    Makeup(String username,int choice){
        this.username=username;
        this.choice=choice;
    }
    // 化妆，互相持有对方想要的锁
    private void makeup() throws InterruptedException {
        if(choice==0){    // have lipstick
            synchronized (lipstick){
                System.out.println(this.username+"获得口红的锁。");
                Thread.sleep(1000);
                // 又想要mirror的锁
                synchronized (mirror){
                    System.out.println(this.username+"1s后又想要镜子的锁。");
                }  // 放在外面
            }
        }else{
            synchronized (mirror){
                System.out.println(this.username+"获得镜子的锁。");
                Thread.sleep(2000);
                // 又想要mirror的锁
                synchronized (lipstick){
                    System.out.println(this.username+"2s后又想要口红的锁。");
                }  // 放在外面
            }
        }
    }
    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}